package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.JsonBean;
import com.wnhz.work.yz.utils.GetJsonDataUtil;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.SwitchView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * ---新增地址
 */
public class AddAddressActivity extends BaseActivity implements View.OnClickListener, SwitchView.OnStateChangedListener {
    private TextView title;
    private TextView tv_right;
    private EditText et_name, et_phone, et_detail_address;
    private TextView tv_address;
    private SwitchView switchButton;

    private String consignee, telephone, province, city, district, place, address;
    private String def = "0";

    private String titles;
    private String name;
    private String phone;
    private String province1;
    private String city1;
    private String district1;
    private String place1;
    private String def1;
    private String addressId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        initJsonData();
        initData();
        initView();
    }

    private void initData() {
        titles = getIntent().getStringExtra("title");
        name = getIntent().getStringExtra("name");
        phone = getIntent().getStringExtra("phone");
        province1 = getIntent().getStringExtra("province");
        city1 = getIntent().getStringExtra("city");
        district1 = getIntent().getStringExtra("district");
        place1 = getIntent().getStringExtra("place");
        def1 = getIntent().getStringExtra("def");
        addressId = getIntent().getStringExtra("addressId");
        //System.out.println(addressId + "     ==ccccccccc");
    }

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-" +
                        options2Items.get(options1).get(options2) + "-" +
                        options3Items.get(options1).get(options2).get(options3);

                tv_address.setText(tx);
                province = options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
                district = options3Items.get(options1).get(options2).get(options3);


                province1 = options1Items.get(options1).getPickerViewText();
                city1 = options2Items.get(options1).get(options2);
                district1 = options3Items.get(options1).get(options2).get(options3);

                // tv_city.setText(tx);
//                Toast.makeText(.this,tx,Toast.LENGTH_SHORT).show();
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色.build();
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        if (options1Items.size() == 0) {
            initJsonData();
            return;
        }
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = GetJsonDataUtil.parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    private void initView() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText(titles);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.submit).setVisibility(View.VISIBLE);
        findViewById(R.id.submit).setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.submit);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("保存");
        tv_right.setTextColor(0xff008c99);

        et_name = (EditText) findViewById(R.id.et_name);
        et_phone = (EditText) findViewById(R.id.et_phone);
        tv_address = (TextView) findViewById(R.id.tv_address);
        et_detail_address = (EditText) findViewById(R.id.et_detail_address);
        switchButton = (SwitchView) findViewById(R.id.switchButton);

        tv_address.setOnClickListener(this);

        switchButton.setOpened(false);
        switchButton.setOnStateChangedListener(this);

        if ("修改地址".equals(titles)) {
            et_name.setText(name);
            et_phone.setText(phone);
            tv_address.setText(province1 + "-" + city1 + "-" + district1);
            et_detail_address.setText(place1);
            if ("1".equals(def1)) {
                switchButton.setOpened(true);
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //保存
            case R.id.submit:
                consignee = et_name.getText().toString();
                telephone = et_phone.getText().toString();
                place = et_detail_address.getText().toString();
                address = tv_address.getText().toString();
                if (!"".equals(consignee) && !"".equals(telephone) && !"".equals(place) && !"".equals(address)) {
                    if ("修改地址".equals(titles)) {
                        upload2();
                    } else {
                        upload();
                    }
                } else if ("".equals(consignee)) {
                    MyToast("收货人不能为空");
                } else if ("".equals(telephone)) {
                    MyToast("手机号码不能为空");
                } else if (telephone.length() != 11) {
                    MyToast("请填写正确手机号");
                } else if ("".equals(address)) {
                    MyToast("地址不能为空");
                } else if ("".equals(place)) {
                    MyToast("详细地址不能为空");
                }
                break;

            //选择地址
            case R.id.tv_address:
//                intent = new Intent(AddAddressActivity.this, AlertAddress.class);
//                startActivityForResult(intent, 115);
//                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                ShowPickerView();
                break;

            default:
                break;
        }
    }

    private void upload2() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("addressId", addressId);
        map.put("consignee", consignee);
        map.put("province", province1);
        map.put("city", city1);
        map.put("district", district1);
        map.put("place", place);
        map.put("telephone", telephone);
        map.put("default", def);

        Log.i(TAG, "upload: telephone= " + addressId);
        Log.i(TAG, "upload: telephone= " + province + city + district);
        Log.i(TAG, "upload: telephone= " + def);


        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }
        XUtil.Post(Url.MEMBER_EDITADDRESS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: telephone = " + result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(AddAddressActivity.this, LoginNewActivity.class));
//                        return;
//                    }
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });

    }

    private static final String TAG = "AddAddressActivity";

    private void upload() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("consignee", consignee);
        map.put("province", province);
        map.put("city", city);
        map.put("district", district);
        map.put("place", place);
        map.put("telephone", telephone);
        map.put("default", def);

        Log.i(TAG, "upload: telephone= " + consignee);
        Log.i(TAG, "upload: telephone= " + province);
        Log.i(TAG, "upload: telephone= " + city);
        Log.i(TAG, "upload: telephone= " + district);
        Log.i(TAG, "upload: telephone= " + place);
        Log.i(TAG, "upload: telephone= " + telephone);
        Log.i(TAG, "upload: telephone= " + def);
        XUtil.Post(Url.MEMBER_ADDADDRESS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: telephone = " + result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
//                    if ("-1".equals(res)) {
//                        //info = "请重新登录";
//                        MyToast("请重新登录");
//                        startActivity(new Intent(AddAddressActivity.this, LoginNewActivity.class));
//                        return;
//                    }
                    if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    } else {
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //地址
            case 115:

                if (resultCode == 333) {
                    if (data != null) {
                        tv_address.setText(data.getStringExtra("address"));
                        province = data.getStringExtra("province");
                        city = data.getStringExtra("city");
                        district = data.getStringExtra("district");
                    }
                }


                break;

            default:
                break;
        }
    }

    @Override
    public void toggleToOn(View view) {
        switchButton.setOpened(true);
        showOrHidePickLayout1(true);
    }

    @Override
    public void toggleToOff(View view) {
        switchButton.setOpened(false);
        showOrHidePickLayout1(false);
    }

    private void showOrHidePickLayout1(boolean isNeedToPick) {

        if (isNeedToPick) {
            def = "1";
        } else {
            def = "0";
        }
    }

}
